/**
 * 权限
 *  
 */
import Taro from "@tarojs/taro";
import type { Auth, UserInfo, UserTypes } from "./types/user";
/**
 * constants
 */
const actionPrefix = `Auth/`;
export const SET_AUTH = actionPrefix + "SET_AUTH";
export const SET_USERINFO = actionPrefix + "SET_USERINFO";
export const CLEAR = actionPrefix + "CLEAR";

/**
 * actions
 */
/**
 * 设置auth
 * @param {}
 * @return
 */
export const setAuth = (auth: Auth) => {
  return {
    type: SET_AUTH,
    auth,
  };
};
/**
 * 设置用户信息
 * @param {}
 * @return
 */
export const setUserInfo = (userInfo: UserInfo) => {
  return {
    type: SET_USERINFO,
    userInfo,
  };
};
/**
 * 清除
 * @param {}
 * @return
 */
export const clear = () => {
  return {
    type: CLEAR,
  };
};

/**
 * state
 */
const INITIAL_STATE: UserTypes = {
  auth: Taro.getStorageSync("auth") || {
    token: undefined,
    exipreTime: undefined,
  },
  userInfo: Taro.getStorageSync("userInfo") || undefined,
};
export default function user(state = INITIAL_STATE, action) {
  switch (action.type) {
    case SET_AUTH:
      Taro.setStorageSync("auth", action.auth);
      return {
        ...state,
        auth: action.auth,
      };
    case SET_USERINFO:
      const userInfo = {
        ...state.userInfo,
        ...action.userInfo,
      };
      Taro.setStorageSync("userInfo", userInfo);
      return {
        ...state,
        userInfo,
      };
    case CLEAR:
      Taro.setStorageSync("auth", undefined);
      Taro.setStorageSync("userInfo", undefined);
      return {
        auth: {
          token: undefined,
          exipreTime: undefined,
        },
        userInfo: undefined,
      };
    default:
      return state;
  }
}
